{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# fill_a_pix"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/fill_a_pix.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/fill_a_pix.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Fill-a-Pix problem in Google CP Solver.\n",
    "\n",
    "  From\n",
    "  http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic\n",
    "  '''\n",
    "  Each puzzle consists of a grid containing clues in various places. The\n",
    "  object is to reveal a hidden picture by painting the squares around each\n",
    "  clue so that the number of painted squares, including the square with\n",
    "  the clue, matches the value of the clue.\n",
    "  '''\n",
    "\n",
    "  http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/rules\n",
    "  '''\n",
    "  Fill-a-Pix is a Minesweeper-like puzzle based on a grid with a pixilated\n",
    "  picture hidden inside. Using logic alone, the solver determines which\n",
    "  squares are painted and which should remain empty until the hidden picture\n",
    "  is completely exposed.\n",
    "  '''\n",
    "\n",
    "  Fill-a-pix History:\n",
    "  http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/history\n",
    "\n",
    "\n",
    "  Compare with the following models:\n",
    "  * MiniZinc: http://www.hakank.org/minizinc/fill_a_pix.mzn\n",
    "  * SICStus Prolog: http://www.hakank.org/sicstus/fill_a_pix.pl\n",
    "  * ECLiPSe: http://hakank.org/eclipse/fill_a_pix.ecl\n",
    "  * Gecode: http://hakank.org/gecode/fill_a_pix.cpp\n",
    "\n",
    "  And see the Minesweeper model:\n",
    "  * http://www.hakank.org/google_or_tools/minesweeper.py\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "# Puzzle 1 from\n",
    "# http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/rules\n",
    "default_n = 10\n",
    "X = -1\n",
    "default_puzzle = [\n",
    "    [X, X, X, X, X, X, X, X, 0, X], [X, 8, 8, X, 2, X, 0, X, X, X],\n",
    "    [5, X, 8, X, X, X, X, X, X, X], [X, X, X, X, X, 2, X, X, X, 2],\n",
    "    [1, X, X, X, 4, 5, 6, X, X, X], [X, 0, X, X, X, 7, 9, X, X, 6],\n",
    "    [X, X, X, 6, X, X, 9, X, X, 6], [X, X, 6, 6, 8, 7, 8, 7, X, 5],\n",
    "    [X, 4, X, 6, 6, 6, X, 6, X, 4], [X, X, X, X, X, X, 3, X, X, X]\n",
    "]\n",
    "\n",
    "\n",
    "def main(puzzle='', n=''):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver('Fill-a-Pix')\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "\n",
    "  # Set default problem\n",
    "  if puzzle == '':\n",
    "    puzzle = default_puzzle\n",
    "    n = default_n\n",
    "  else:\n",
    "    print('n:', n)\n",
    "\n",
    "  # for the neighbors of 'this' cell\n",
    "  S = [-1, 0, 1]\n",
    "\n",
    "  # print problem instance\n",
    "  print('Problem:')\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      if puzzle[i][j] == X:\n",
    "        sys.stdout.write('.')\n",
    "      else:\n",
    "        sys.stdout.write(str(puzzle[i][j]))\n",
    "    print()\n",
    "  print()\n",
    "\n",
    "  #\n",
    "  # declare variables\n",
    "  #\n",
    "  pict = {}\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      pict[(i, j)] = solver.IntVar(0, 1, 'pict %i %i' % (i, j))\n",
    "\n",
    "  pict_flat = [pict[i, j] for i in range(n) for j in range(n)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      if puzzle[i][j] > X:\n",
    "        # this cell is the sum of all the surrounding cells\n",
    "        solver.Add(puzzle[i][j] == solver.Sum([\n",
    "            pict[i + a, j + b]\n",
    "            for a in S\n",
    "            for b in S\n",
    "            if i + a >= 0 and j + b >= 0 and i + a < n and j + b < n\n",
    "        ]))\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  db = solver.Phase(pict_flat, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT)\n",
    "\n",
    "  solver.NewSearch(db)\n",
    "  num_solutions = 0\n",
    "  print('Solution:')\n",
    "  while solver.NextSolution():\n",
    "    num_solutions += 1\n",
    "    for i in range(n):\n",
    "      row = [str(pict[i, j].Value()) for j in range(n)]\n",
    "      for j in range(n):\n",
    "        if row[j] == '0':\n",
    "          row[j] = ' '\n",
    "        else:\n",
    "          row[j] = '#'\n",
    "      print(''.join(row))\n",
    "    print()\n",
    "\n",
    "  print('num_solutions:', num_solutions)\n",
    "  print('failures:', solver.Failures())\n",
    "  print('branches:', solver.Branches())\n",
    "  print('WallTime:', solver.WallTime(), 'ms')\n",
    "\n",
    "\n",
    "#\n",
    "# Read a problem instance from a file\n",
    "#\n",
    "def read_problem(file):\n",
    "  f = open(file, 'r')\n",
    "  n = int(f.readline())\n",
    "  puzzle = []\n",
    "  for i in range(n):\n",
    "    x = f.readline()\n",
    "    row = [0] * n\n",
    "    for j in range(n):\n",
    "      if x[j] == '.':\n",
    "        tmp = -1\n",
    "      else:\n",
    "        tmp = int(x[j])\n",
    "      row[j] = tmp\n",
    "    puzzle.append(row)\n",
    "  return [puzzle, n]\n",
    "\n",
    "\n",
    "if len(sys.argv) > 1:\n",
    "  file = sys.argv[1]\n",
    "  print('Problem instance from', file)\n",
    "  [puzzle, n] = read_problem(file)\n",
    "  main(puzzle, n)\n",
    "else:\n",
    "  main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
